$(function () {

    /*补一下上传*/
    var data4Vue = {
        user:{id:'',name:'',password:'', userImg:''},
        previewSrc: null,
        imageFile: null,
        welUrl:"/welUser",
        addCategoryUrl:"/addCategory",
        deleteCategoryUrl:"/deleteCategory",
        updateCategoryUrl:"/updateCategory",
        listCategory:"/listCategory",
        listAccount:"/listAccount",
        addAccountUrl:"/addAccount",
        deleteAccountUrl:"/deleteAccount",
        updateAccountUrl:"/updateAccount",
        listRecordUrl:"/listRecord",
        listAllRecordUrl:"/listAllRecord",
        addRecordUrl:"/addRecord",
        deleteRecordUrl:"/deleteRecord",
        updateRecordUrl:"/updateRecord",
        monthCostUrl:"/monthRecord",
        setConfigUrl:"/setConfig",
        listDreamUrl:"/listDream",
        addDreamUrl:"/addDream",
        updateDreamUrl:"/updateDream",
        deleteDreamUrl:"/deleteDream",
        updateStateUrl:"/updateState",
        addOfCategory:{id:'',name:'',uid:'', incomeExpend:''},
        updateOfCategory:{id:'',name:'',uid:''},
        category:{id:'',name:'',uid:''},
        expendCategories:[],
        expendCategoriesName:[],
        expendCategoriesSpend:[],
        incomeCategories:[],
        incomeCategoriesName:[],
        incomeCategoriesSpend:[],
        addOfAccount:{id:'', accountName:'', accountType:'', amount:'' ,uid:''},
        updateOfAccount:{id:'', accountName:'', accountType:'', amount:'' ,uid:''},
        accounts:[],
        expendRecord:{id:'',spend:'',cid:'',comment:'',date:'',uid:'', aid:'', incomeExpend:'0'},
        incomeRecord:{id:'',spend:'',cid:'',comment:'',date:'',uid:'', aid:'', incomeExpend:'1'},
        updateRecordInfo:{id:'',spend:'',cid:'',comment:'',date:'',uid:'', aid:'', incomeExpend:''},
        expendRecordList:[],
        incomeRecordList:[],
        monthCost:[],
        monthIncome:[],
        config:{id:'',value:'',uid:''},
        costChart:{monthCost:'',todayCost:'',surplusCost:'',dailyAvg:'',dailyUse:'',surplusDay:'', budgetAdvice: '', budgetWarning: false},
        dreams:[],
        dream:{},
        addDreamInfo:{id:'', theme:'', content:''},
        updateDreamInfo:{id:'', theme:'', content:''},
        dataChart:[],
        recordInfo:[],
        isShowBackToTop: false,
        activeTabIndex: 0,
        // 分页相关数据
        currentPage: 1,        // 当前页码
        pageSize: 10,          // 每页显示条数
        jumpToPage: 1          // 跳转页码
    };
    const vue = new Vue({
        el: "#workArea",
        data: data4Vue,
        mounted: function () {
            this.welcomeName();
            this.loadRecord();
            this.loadCategory();
            this.loadChart();
            this.loadCostChart();
            this.loadAccount();
            this.loadDream();
            this.loadRecordInfo();
            this.checkActiveTab();
            
            // 监听滚动事件
            window.addEventListener('scroll', this.handleScroll);
        },
        beforeDestroy() {
            // 组件销毁前移除事件监听
            window.removeEventListener('scroll', this.handleScroll);
        },
        updated: function () {
            layui.form.render(null, 'formTest');
            layui.form.render('select');
        },
        computed: {
            // 计算总页数
            totalPages() {
                return Math.ceil(this.recordInfo.length / this.pageSize);
            },
            // 获取当前页的数据
            paginatedRecordInfo() {
                const start = (this.currentPage - 1) * this.pageSize;
                const end = start + this.pageSize;
                return this.recordInfo.slice(start, end);
            },
            // 计算要显示的页码
            displayedPages() {
                const pages = [];
                // 总页数小于等于7，显示所有页码
                if (this.totalPages <= 7) {
                    for (let i = 1; i <= this.totalPages; i++) {
                        pages.push(i);
                    }
                } else {
                    // 当前页码在前3页
                    if (this.currentPage <= 3) {
                        for (let i = 1; i <= 5; i++) {
                            pages.push(i);
                        }
                        pages.push('...');
                        pages.push(this.totalPages);
                    }
                    // 当前页码在后3页
                    else if (this.currentPage >= this.totalPages - 2) {
                        pages.push(1);
                        pages.push('...');
                        for (let i = this.totalPages - 4; i <= this.totalPages; i++) {
                            pages.push(i);
                        }
                    }
                    // 当前页码在中间
                    else {
                        pages.push(1);
                        pages.push('...');
                        for (let i = this.currentPage - 1; i <= this.currentPage + 1; i++) {
                            pages.push(i);
                        }
                        pages.push('...');
                        pages.push(this.totalPages);
                    }
                }
                return pages;
            }
        },
        methods: {
            handleScroll() {
                // 只在消费账单和区块信息页面处理滚动事件
                if (this.activeTabIndex === 5 || this.activeTabIndex === 8) {
                    const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
                    this.isShowBackToTop = scrollTop > 300;
                }
            },
            checkActiveTab: function() {
                // 获取当前活动的标签页
                const activeTab = document.querySelector('.layui-tab-title li.layui-this');
                if (activeTab) {
                    const tabIndex = Array.from(activeTab.parentNode.children).indexOf(activeTab);
                    this.activeTabIndex = tabIndex;
                    
                    // 判断是否是消费账单(第6个标签页)或区块信息(第9个标签页)
                    this.isShowBackToTop = (tabIndex === 5 || tabIndex === 8) && window.pageYOffset > 300;
                }
            },
            welcomeName: function () {
                const url = this.welUrl;
                axios.get(url).then(function (value) {
                    vue.user = value.data.data;
                    if (!vue.user.userImg) {
                        vue.previewSrc = "/head/default.jpg"
                    } else {
                        vue.previewSrc = "/head/" + vue.user.userImg
                    }
                })
            },
            //修改用户信息
            updateUserInfo: function () {
                layer.open({
                    type: 1,
                    title: '个人信息',
                    area: ['400px', '480px'],
                    content: $('#userInfo'),
                    btn: ['更新', '取消'],
                    btnAlign: 'c',
                    yes: function (index) {
                        // 确认密码
                        const confirmPassword = $('#reg-password').val();
                        if (vue.user.password !== confirmPassword) {
                            layer.msg("新密码和确认密码不一致！")
                            return;
                        }

                        vue.uploadImage()

                        axios.put('/updateUser', vue.user).then(function (data) {
                            if (data.data.code === 0) {
                                // 显示消息
                                layer.msg(data.data.message, {
                                    time: 1000, // 消息停留1秒
                                    end: function () {
                                        // 消息关闭后的回调函数
                                        location.href = 'login';
                                        vue.welcomeName();
                                        layer.close(index);
                                        $('#reg-password').val('');
                                    }
                                });
                            } else {
                                layer.msg(data.data.message);
                            }
                        })

                    },
                    btn2: function (index) {
                        vue.welcomeName();
                        $('#reg-password').val('');
                    }
                })
            },
            //上传头像
            uploadImage() {
                if (!this.imageFile) {
                    return;
                }

                const formData = new FormData(); // 创建 FormData 对象
                formData.append('file', this.imageFile); // 添加文件到 FormData

                console.log(formData.get('file'));

                axios.post('/upload', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data', // 设置请求头
                    },
                })
            },

            triggerFileInput() {
                this.$refs.fileInput.click(); // 触发文件选择输入框的点击事件
            },

            handleFileChange(event) {
                const file = event.target.files[0]; // 获取选择的文件
                if (file && file.type.match('image.*')) {
                    const reader = new FileReader(); // 创建 FileReader 对象

                    reader.onload = (e) => { // 当文件被读取时触发
                        this.previewSrc = e.target.result; // 设置预览图的 src
                    };
                    reader.readAsDataURL(file); // 读取文件内容

                    this.imageFile = file; // 保存文件到 data 中，以便上传
                } else {
                    alert('请选择一个图片文件。');
                }
            },

            loadChart: function () {
                const url = this.monthCostUrl;
                axios.get(url + '/0').then(function (value) {
                    const data = value.data;
                    if (data.code === 0) {
                        vue.monthCost = data.data;
                        const ctx = document.getElementById('expendChart').getContext('2d');
                        const ctx2 = document.getElementById('expendChartPie').getContext('2d');
                        const myChart = new Chart(ctx, {
                            type: 'bar',
                            data: {
                                labels: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
                                datasets: [{
                                    label: '今年月消费柱状图',
                                    data: vue.monthCost,
                                    borderColor: 'blue',
                                    borderWidth: 1,
                                    fill: false
                                }]
                            },
                            options: {
                                tooltips: {
                                    intersect: false,
                                    mode: 'index'
                                }
                            }
                        });
                        const chartPie = new Chart(ctx2, {
                            type: 'pie',
                            data: {
                                labels: vue.expendCategoriesName,
                                datasets: [{
                                    label: '消费分类占比',
                                    data: vue.expendCategoriesSpend,
                                    borderColor: 'lightGray',
                                    backgroundColor: vue.generateRandomColors(vue.expendCategoriesName.length),
                                    borderWidth: 1
                                }]
                            }
                        });
                    } else {
                        console.log("加载今年月消费记录失败！")
                    }
                });
                axios.get(url + '/1').then(function (value) {
                    const data = value.data;
                    if (data.code === 0) {
                        vue.monthIncome = data.data;
                        const ctx = document.getElementById('incomeChart').getContext('2d');
                        const ctx2 = document.getElementById('incomeChartPie').getContext('2d');
                        const myChart = new Chart(ctx, {
                            type: 'bar',
                            data: {
                                labels: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
                                datasets: [{
                                    label: '今年月收入柱状图',
                                    data: vue.monthIncome,
                                    borderColor: 'blue',
                                    borderWidth: 1,
                                    fill: false
                                }]
                            },
                            options: {
                                tooltips: {
                                    intersect: false,
                                    mode: 'index'
                                }
                            }
                        });
                        const chartPie = new Chart(ctx2, {
                            type: 'pie',
                            data: {
                                labels: vue.incomeCategoriesName,
                                datasets: [{
                                    label: '今年月收入饼图',
                                    data: vue.incomeCategoriesSpend,
                                    borderColor: 'lightGray',
                                    backgroundColor: vue.generateRandomColors(vue.incomeCategoriesName.length),
                                    borderWidth: 1
                                }]
                            }
                        });
                    } else {
                        console.log("加载今年月收入记录失败！")
                    }
                });
            },
            // 函数：生成随机颜色数组
             generateRandomColors(count) {
                const colors = [];
                for (let i = 0; i < count; i++) {
                    // 生成随机颜色
                    const color = `#${Math.floor(Math.random() * 16777215).toString(16)}`;
                    colors.push(color);
                }
                return colors;
             },

            loadCostChart: function () {
                const costUrl = "/costChart/0";
                axios.get(costUrl).then(function (value) {
                    const data = value.data;
                    if (data.code === 0) {
                        vue.costChart = data.data;
                        vue.dataChart[0] = vue.costChart.monthCost;
                        vue.dataChart[1] = vue.costChart.surplusCost;
                        
                        // 分析剩余金额占比并生成建议
                        vue.analyzeBudget();
                        
                        const ctxx = document.getElementById('doughnutCost').getContext('2d');
                        const myCharts = new Chart(ctxx, {
                            type: 'doughnut',
                            data: {
                                labels: ['已消费', '未消费'],
                                datasets: [{
                                    label: '本月消费图',
                                    data: vue.dataChart,
                                    borderColor: 'lightGray',
                                    backgroundColor: ['#FFA500 ', '#87CEEB'],
                                    borderWidth: 1
                                }]
                            },
                            options: {
                                responsive: true,
                                maintainAspectRatio: false,
                                cutout: '55%',
                                layout: {
                                    padding: 20
                                },
                                plugins: {
                                    legend: {
                                        display: false
                                    },
                                    tooltip: {
                                        callbacks: {
                                            label: function(context) {
                                                const value = context.parsed;
                                                const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                                const percentage = Math.round((value / total) * 100);
                                                return `${context.label}: ¥${value} (${percentage}%)`;
                                            }
                                        },
                                        titleFont: {
                                            size: 14
                                        },
                                        bodyFont: {
                                            size: 14
                                        },
                                        padding: 10
                                    }
                                }
                            }
                        });
                    } else {
                        console.log("加载月消费一览图失败！");
                    }
                })
            },
            
            // 分析预算消费情况并生成建议
            analyzeBudget: function() {
                // 初始化建议和警告信息
                vue.costChart.budgetAdvice = '';
                vue.costChart.budgetWarning = false;
                
                // 计算已使用预算的百分比
                const totalBudget = parseFloat(vue.costChart.monthCost) + parseFloat(vue.costChart.surplusCost);
                if (totalBudget <= 0) {
                    vue.costChart.budgetAdvice = '您尚未设置预算，请在预算设置页面设置本月预算';
                    return;
                }
                
                // 强制转换为数字以确保计算正确
                const monthCost = parseFloat(vue.costChart.monthCost);
                const surplusCost = parseFloat(vue.costChart.surplusCost);
                const surplusDay = parseInt(vue.costChart.surplusDay);
                
                const usedPercentage = (monthCost / totalBudget) * 100;
                const remainingPercentage = (surplusCost / totalBudget) * 100;
                
                console.log("预算分析: 总预算=" + totalBudget + ", 已用=" + usedPercentage.toFixed(2) + 
                          "%, 剩余=" + remainingPercentage.toFixed(2) + "%, 剩余天数=" + surplusDay);
                
                // 根据剩余预算百分比给出建议
                if (remainingPercentage <= 10) {
                    vue.costChart.budgetAdvice = '警告：预算即将用尽！建议控制支出，减少非必要消费。';
                    vue.costChart.budgetWarning = true;
                } else if (remainingPercentage <= 20) {
                    vue.costChart.budgetAdvice = '注意：预算剩余不足20%，请谨慎消费。';
                    vue.costChart.budgetWarning = true;
                } else if (remainingPercentage <= 30) {
                    vue.costChart.budgetAdvice = '提示：预算已消费超过70%，可能需要控制一下支出。';
                } else if (remainingPercentage >= 70 && surplusDay <= 10) {
                    vue.costChart.budgetAdvice = '很好！您的消费控制得当，剩余预算充足。';
                } else if (usedPercentage >= 70 && surplusDay >= 20) {
                    vue.costChart.budgetAdvice = '消费速度偏快，建议降低日均消费。';
                } else if (usedPercentage <= 30 && surplusDay <= 10) {
                    vue.costChart.budgetAdvice = '消费速度合理，继续保持良好的消费习惯。';
                } else {
                    vue.costChart.budgetAdvice = '消费情况正常，请继续保持合理消费。';
                }
            },

            loadCategory: function () {
                const url = this.listCategory;
                axios.get(url + '/0').then(function (value) {
                    const data = value.data;
                    if (data.code === 0) {
                        vue.expendCategories = data.data;
                        vue.expendCategories.forEach((value) => {
                            vue.expendCategoriesName.push(value.name)
                            vue.expendCategoriesSpend.push(value.totalMoney)
                        })
                    } else {
                        console.log("加载失败！")
                    }
                })

                axios.get(url + '/1').then(function (value) {
                    const data = value.data;
                    if (data.code === 0) {
                        vue.incomeCategories = data.data;
                        vue.incomeCategories.forEach((value) => {
                            vue.incomeCategoriesName.push(value.name)
                            vue.incomeCategoriesSpend.push(value.totalMoney)
                        })
                    } else {
                        console.log("加载失败！")
                    }
                })
            },
            loadAccount: function () {
                const url = this.listAccount;
                axios.get(url).then(function (value) {
                    const data = value.data;
                    if (data.code === 0) {
                        vue.accounts = data.data;
                    } else {
                        console.log("加载失败！")
                    }
                })
            },
            loadDream: function () {
                const url = this.listDreamUrl;
                axios.get(url).then(function (value) {
                    const data = value.data;
                    if (data.code === 0) {
                        vue.dreams = data.data;
                    } else {
                        console.log("加载失败！")
                    }
                })
            },
            loadRecordInfo:function (){
                const url = this.listAllRecordUrl;
                axios.get(url).then(function (value){
                    const data =value.data;
                    if (data.code === 0){
                        vue.recordInfo = data.data;
                        // 加载数据后重置分页到第一页
                        vue.currentPage = 1;
                    }else {
                        console.log("加载失败")
                    }
                })
            },
            addDream: function () {
                layer.open({
                    type: 1,
                    title: '增加心愿',
                    area: ['400px', '300px'],
                    content: $("#addDreamInfo"),
                    btn: '确认添加',
                    yes: function (index) {
                        if (vue.addDreamInfo.theme === '' || vue.addDreamInfo.content === ''){
                            layer.msg("请填完全部选项！")
                            return;
                        }
                        const url = vue.addDreamUrl;
                        axios.post(url, vue.addDreamInfo).then(function (value) {
                            const data = value.data;
                            if (data.code === 0) {
                                layer.msg("添加成功");
                                vue.loadDream();
                                layer.close(index);
                                vue.addDreamInfo.theme = '';
                                vue.addDreamInfo.content = '';
                            } else {
                                layer.msg("添加失败");
                            }
                        })
                    }
                })
            },
            updateDream(id, theme, content) {
                vue.updateDreamInfo.theme = theme;
                vue.updateDreamInfo.content = content;
                vue.updateDreamInfo.id = id;
                layer.open({
                    type: 1,
                    title: '您正在对心愿进行编辑',
                    area: ['400px', '300px'],
                    content: $('#updateDreamInfo'),
                    btn: ['确认', '取消'],
                    yes: function (index) {
                        if (vue.updateDreamInfo.theme === '' || vue.updateDreamInfo.content === '') {
                            layer.msg("主题或内容不能为空！");
                            return;
                        }
                        const url = vue.updateDreamUrl;
                        axios.put(url, vue.updateDreamInfo).then(function (value) {
                            const data = value.data;
                            if (data.code === 0) {
                                layer.msg("更新成功！");
                                vue.updateDreamInfo.theme = '';
                                vue.updateDreamInfo.content = '';
                                vue.updateDreamInfo.id = '';
                                vue.loadDream();
                            } else {
                                layer.msg("更新失败！");
                            }
                        });
                        layer.close(index);
                    },
                    '取消': function (index) {

                    }
                })
            },
            deleteDream: function (id) {
                layer.open({
                    type: 1,
                    title: '您确认要删除该心愿吗？',
                    area: ['350px', '150px'],
                    content: '<div style="padding: 20px; text-align: center;">删除后将无法恢复，是否继续？</div>',
                    btn: ['确认', '取消'],
                    yes: function (index) {
                        layer.close(index);
                        vue.dream.id = id;
                        axios.post(vue.deleteDreamUrl, vue.dream).then(function (value) {
                            const data = value.data;
                            if (data.code === 0) {
                                layer.msg("删除成功！");
                                vue.dream.id = '';
                                vue.loadDream();
                            } else {
                                layer.msg("删除失败！");
                            }
                        })
                    },
                    '取消': function (index) {

                    }
                })
            },
            updateState: function (id) {
                layer.open({
                    type: 1,
                    title: '该心愿已达成',
                    area: ['350px', '150px'],
                    content: '<div style="padding: 20px; text-align: center;">确认将该心愿标记为已达成？</div>',
                    btn: ['确认', '取消'],
                    yes: function (index) {
                        layer.close(index);
                        vue.dream.id = id;
                        axios.put(vue.updateStateUrl, vue.dream).then(function (value) {
                            const data = value.data;
                            if (data.code === 0) {
                                layer.msg("完成心愿！");
                                vue.dream.id = '';
                                vue.loadDream();
                            } else {
                                layer.msg("达成失败！");
                            }
                        })
                    },
                    '取消': function (index) {

                    }
                })
            },
            deleteCategory: function (id) {
                layer.open({
                    type: 1,
                    title: '您确认要删除该条分类吗？',
                    area: ['400px', '180px'],
                    content: '<div style="color: red; padding: 20px; text-align: center;">删除该分类，该分类下的记录也会被删除！</div>',
                    btn: ['确认', '取消'],
                    yes: function (index) {
                        layer.close(index);
                        vue.addOfCategory.id = id;
                        axios.post(vue.deleteCategoryUrl, vue.addOfCategory).then(function (value) {
                            var data = value.data;
                            if (data.code === 0) {
                                layer.msg("删除成功！");
                                vue.addOfCategory.name = '';
                                vue.addOfCategory.id = '';
                                vue.loadCategory();
                                vue.loadRecord();
                            } else {
                                layer.msg("删除失败！");
                            }
                        })
                    },
                    '取消': function (index) {

                    }
                })
            },
            updateCategory(id, name) {
                vue.updateOfCategory.name = name;
                vue.updateOfCategory.id = id;
                layer.open({
                    type: 1,
                    title: '您正在对该条分类进行编辑',
                    area: ['400px', '250px'],
                    content: $('#updateCategoryInfo'),
                    btn: ['确认', '取消'],
                    yes: function (index) {
                        var url = vue.updateCategoryUrl;
                        axios.put(url, vue.updateOfCategory).then(function (value) {
                            var data = value.data;
                            if (data.code === 0) {
                                layer.msg("更新成功！");
                                vue.updateOfCategory.id = '';
                                vue.updateOfCategory.name = '';
                                vue.updateOfCategory.uid = '';
                                vue.loadCategory();
                                vue.loadRecord();
                            } else {
                                layer.msg("更新失败！");
                            }
                        });
                        layer.close(index);
                    },
                    '取消': function (index) {

                    }
                })
            },
            funAddCategory: function () {
                if (vue.addOfCategory.name !== '' && vue.addOfCategory.incomeExpend !== '') {
                    const url = vue.addCategoryUrl;
                    axios.post(url, vue.addOfCategory).then(function (value) {
                        const data = value.data;
                        if (data.code === 0) {
                            layer.msg("添加成功");
                            vue.loadCategory();
                            vue.addOfCategory.name = '';
                            vue.addOfCategory.incomeExpend = '';
                        } else {
                            layer.msg("添加失败");
                        }
                    })
                }
            },
            checkAmount: function () {
                let price = '' + this.addOfAccount.amount;
                price = this.checked(price);
                this.addOfAccount.amount = price;
            },
            addAccount: function (data) {
                layer.open({
                    type: 1,
                    title: '增加账户',
                    area: ['400px', '350px'],
                    content: $("#addAccountInfo"),
                    btn: '确认添加',
                    yes: function (index) {
                        if (vue.addOfAccount.accountName === '' || vue.addOfAccount.accountType === '' || vue.addOfAccount.amount === ''){
                            layer.msg("请填完全部选项！")
                            return;
                        }
                        const url = vue.addAccountUrl;
                        axios.post(url, vue.addOfAccount).then(function (value) {
                            const data = value.data;
                            if (data.code === 0) {
                                layer.msg("添加成功");
                                vue.loadAccount();
                                layer.close(index);
                                vue.addOfAccount.accountName = '';
                                vue.addOfAccount.accountType = '';
                                vue.addOfAccount.amount = '';
                            } else {
                                layer.msg("添加失败");
                            }
                        })
                    }
                })
            },
            deleteAccount: function (id) {
                layer.open({
                    type: 1,
                    title: '您确认要删除该账户吗？',
                    area: ['400px', '180px'],
                    content: '<div style="color: red; padding: 20px; text-align: center;">删除该账户，该账户下的记录也会被删除！</div>',
                    btn: ['确认', '取消'],
                    yes: function (index) {
                        layer.close(index);
                        vue.addOfAccount.id = id;
                        axios.post(vue.deleteAccountUrl, vue.addOfAccount).then(function (value) {
                            const data = value.data;
                            if (data.code === 0) {
                                layer.msg("删除成功！");
                                vue.addOfAccount.id = '';
                                vue.loadAccount();
                                vue.loadRecord();
                            } else {
                                layer.msg("删除失败！");
                            }
                        })
                    },
                    '取消': function (index) {

                    }
                })
            },
            updateAccount(id, accountName, accountType, amount) {
                vue.updateOfAccount.accountName = accountName;
                vue.updateOfAccount.accountType = accountType;
                vue.updateOfAccount.amount = amount;
                vue.updateOfAccount.id = id;
                layer.open({
                    type: 1,
                    title: '您正在对该账户进行编辑',
                    area: ['400px', '350px'],
                    content: $('#updateAccountInfo'),
                    btn: ['确认', '取消'],
                    yes: function (index) {
                        if (vue.updateOfAccount.amount === '' || vue.updateOfAccount.accountName === '') {
                            layer.msg("账户名称或账户余额不能为空！");
                            return;
                        }
                        const url = vue.updateAccountUrl;
                        axios.put(url, vue.updateOfAccount).then(function (value) {
                            const data = value.data;
                            if (data.code === 0) {
                                layer.msg("更新成功！");
                                vue.updateOfAccount.accountName = '';
                                vue.updateOfAccount.accountType = '';
                                vue.updateOfAccount.amount = '';
                                vue.updateOfAccount.id = '';
                                vue.loadAccount();
                                vue.loadRecord();
                            } else {
                                layer.msg("更新失败！");
                            }
                        });
                        layer.close(index);
                    },
                    '取消': function (index) {

                    }
                })
            },
            addExpendRecord: function () {
                if (vue.expendRecord.date === '' || vue.expendRecord.spend === '' || vue.expendRecord.cid === '' || vue.expendRecord.aid === '') {
                    layer.msg("除备注外，其余选项不能为空！")
                    return;
                }
                const url = this.addRecordUrl;
                axios.post(url, vue.expendRecord).then(function (value) {
                    const data = value.data;
                    if (data.code === 0) {
                        vue.expendRecord.comment = '';
                        vue.expendRecord.date = '';
                        vue.expendRecord.spend = '';
                        vue.expendRecord.cid = '';
                        vue.expendRecord.aid = '';
                        layer.msg("记录成功！且将数据上传到了区块链！");
                        vue.loadRecord();
                        vue.loadAccount();
                        vue.loadChart();
                        vue.loadCostChart();
                        vue.loadRecordInfo();
                        vue.loadAccount();
                    } else {
                        layer.msg("记录失败！余额不足。")
                    }
                })
            },
            addIncomeRecord: function () {
                if (vue.incomeRecord.date === '' || vue.incomeRecord.spend === '' || vue.incomeRecord.cid === '' || vue.incomeRecord.aid === '') {
                    layer.msg("除备注外，其余选项不能为空！")
                    return;
                }
                const url = this.addRecordUrl;
                axios.post(url, vue.incomeRecord).then(function (value) {
                    const data = value.data;
                    if (data.code === 0) {
                        vue.incomeRecord.comment = '';
                        vue.incomeRecord.date = '';
                        vue.incomeRecord.spend = '';
                        vue.incomeRecord.cid = '';
                        vue.incomeRecord.aid = '';
                        layer.msg("记录成功！");
                        vue.loadAccount();
                        vue.loadRecord();
                        vue.loadChart();
                        vue.loadCostChart();
                        vue.loadRecordInfo();
                    } else {
                        layer.msg("记录失败！请重试。")
                    }
                })
            },
            checked: function (price) {
                price = price
                    .replace(/[^\d.]/g, '') // 清除"数字"和"."以外的字符
                    .replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
                    .replace('.', '$#$')
                    .replace(/\./g, '')
                    .replace('$#$', '.')
                    .replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); // 只能输入两个小数
                if (price.indexOf('.') < 0 && price !== '') {
                    // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
                    price = parseFloat(price);
                }
                return price;
            },
            checkSpend: function () {
                let price = '' + this.expendRecord.spend;
                price = this.checked(price);
                this.expendRecord.spend = price;
            },
            checkIncome: function () {
                let price = '' + this.incomeRecord.spend;
                price = this.checked(price);
                this.incomeRecord.spend = price;
            },
            checkConf: function () {
                let price = '' + this.config.value;
                price = this.checked(price)
                this.config.value = price;
            },
            loadRecord: function () {
                const url = this.listRecordUrl;
                axios.get(url + '/0').then(function (value) {
                    const data = value.data;
                    if (data.code === 0) {
                        vue.expendRecordList = data.data;
                    } else {
                        console.log("加载账单失败!");
                    }
                });

                axios.get(url + '/1').then(function (value) {
                    const data = value.data;
                    if (data.code === 0) {
                        vue.incomeRecordList = data.data;
                    } else {
                        console.log("加载账单失败!");
                    }
                });
            },
            deleteRecord: function (id) {
                layer.open({
                    type: 1,
                    title: '您确认要删除该条记录吗？',
                    area: ['350px', '180px'],
                    content: '<div style="padding: 20px; text-align: center;">删除后将无法恢复，是否继续？</div>',
                    btn: ['确认', '取消'],
                    yes: function (index) {
                        layer.close(index);
                        axios.post(vue.deleteRecordUrl + '/' + id).then(function (value) {
                            const data = value.data;
                            if (data.code === 0) {
                                layer.msg("删除成功！");
                                vue.loadRecord();
                                vue.loadChart();
                                vue.loadCostChart();
                                vue.loadCategory();
                            } else {
                                layer.msg("删除失败！");
                            }
                        })
                    },
                    '取消': function (index) {

                    }
                })
            },
            checkNewSpend: function () {
                let price = '' + this.updateRecordInfo.spend;
                price = this.checked(price);
                this.updateRecordInfo.spend = price;
            },
            updateRecord(id, date, spend, cid, comment, aid, incomeExpend) {
                vue.updateRecordInfo.id = id;
                vue.updateRecordInfo.cid = cid;
                vue.updateRecordInfo.date = date;
                vue.updateRecordInfo.spend = spend;
                vue.updateRecordInfo.comment = comment;
                vue.updateRecordInfo.aid = aid;
                vue.updateRecordInfo.incomeExpend = incomeExpend;

                layer.open({
                    type: 1,
                    title: '您正在对该条记录进行编辑',
                    area: ['450px', '500px'],
                    content: $('#updateRecord'),
                    btn: ['确认', '取消'],
                    yes: function (index) {
                        if (vue.updateRecordInfo.spend === '' || vue.updateRecordInfo.spend === 0) {
                            layer.msg("花销不能为空或0！");
                            return;
                        }
                        axios.put(vue.updateRecordUrl, vue.updateRecordInfo).then(function (value) {
                            const data = value.data;
                            if (data.code === 0) {
                                layer.msg("更新成功！");
                                vue.updateRecordInfo.id = '';
                                vue.updateRecordInfo.cid = '';
                                vue.updateRecordInfo.date = '';
                                vue.updateRecordInfo.spend = '';
                                vue.updateRecordInfo.comment = '';
                                vue.updateRecordInfo.aid = '';
                                vue.updateRecordInfo.incomeExpend = '';
                                vue.loadRecord();
                                vue.loadChart();
                                vue.loadCostChart();
                                vue.loadCategory();
                            } else {
                                layer.msg("更新失败！");
                            }
                        });
                        layer.close(index);
                    },
                    '取消': function (index) {

                    }
                })
            },
            toTop: function () {
                // 平滑滚动到顶部
                window.scrollTo({
                    top: 0,
                    behavior: 'smooth'
                });
            },
            quit: function () {
                const url = "/quit";
                axios.get(url).then(function (value) {
                    const data = value.data;
                    if (data.code == 0) {
                        window.location.href = '/login';
                    } else {
                        layer.msg("系统繁忙，请稍后再试。")
                    }
                })
            },
            setConfig: function () {
                const url = this.setConfigUrl;
                if (this.config.value !== '') {
                    axios.post(url, vue.config).then(function (value) {
                        const data = value.data;
                        if (data.code === 0) {
                            layer.msg("设置成功！");
                            vue.config.value = '';
                            vue.loadCostChart();
                        } else {
                            layer.msg("设置失败！");
                        }
                    })
                }
            },
            // 分页相关方法
            goToPage: function(page) {
                if (page < 1) {
                    page = 1;
                } else if (page > this.totalPages) {
                    page = this.totalPages;
                }
                this.currentPage = page;
                this.jumpToPage = page;
            },
            handlePageSizeChange: function() {
                // 切换每页显示条数时，重置到第一页
                this.currentPage = 1;
                this.jumpToPage = 1;
            }
        }
    });

    layui.use('layer', function(){
        const layer = layui.layer;
        $('#addLayer').click(function () {
            layer.open({
                type: 1,
                title: '增加分类',
                area: ['400px', '300px'],
                content: $("#addCategoryInfo"),
                btn:'确认添加',
                yes: function(index){
                    layer.close(index);
                    vue.funAddCategory();
                }
            })
        })
    });
    layui.use('element', function(){
        const element = layui.element;

        //监听标签页切换
        element.on('tab(demo)', function(data){
            vue.activeTabIndex = data.index;
            // 判断是否是消费账单(第6个标签页)或区块信息(第9个标签页)
            vue.isShowBackToTop = (data.index === 5 || data.index === 8) && window.pageYOffset > 300;
        });
    });
    layui.use('laydate', function(){
        const laydate = layui.laydate;
        const $ = layui.$;
        //执行一个laydate实例
        laydate.render({
            elem: '#timeSelectA, #timeSelectB, #timeUpdate' //指定元素
            ,type: 'datetime' //设置选择类型为日期时间
            ,format: 'yyyy-MM-dd HH:mm:ss', //设置日期时间格式
            done: function (value) {
                // 获取当前时间选择器的id
                const id = $(this).attr('id');
                // 根据id区分不同的时间选择器，更新对应的 Vue 实例属性
                if (id === 'timeUpdate') {
                    vue.updateRecordInfo.date = value;
                }
                if (id === 'timeSelectA') {
                    vue.expendRecord.date = value;
                }
                if (id === 'timeSelectB') {
                    vue.incomeRecord.date = value;
                }
            }
        });
    });
    layui.use('form', function(){
        const form = layui.form;
        form.on('select(selectIncomeCategory)', function (data) {
            vue.incomeRecord.cid = data.value
        });

        form.on('select(selectExpendCategory)', function (data) {
            vue.expendRecord.cid = data.value
        })

        form.on('select(selectExpendAccount)', function (data) {
            vue.expendRecord.aid = data.value
        });

        form.on('select(selectIncomeAccount)', function (data) {
            vue.incomeRecord.aid = data.value
        });

        form.on('select(updateC)', function (data) {
            vue.updateRecordInfo.cid = data.value
        });

        form.on('select(updateA)', function (data) {
            vue.updateRecordInfo.aid = data.value
        });

        form.on('select(updateAT)', function (data) {
            vue.updateOfAccount.accountType = data.value
        });

        form.on('select(addC)', function (data) {
            vue.addOfCategory.incomeExpend = data.value
        });

        form.on('select(addA)', function (data) {
            vue.addOfAccount.accountType = data.value
        });
    });

});